"use client";

import { useEffect, useMemo, useState } from "react";
import type { CategoryItem, VideoCategory, VideoItem } from "@/app/types/video";

type FormMode = "create" | "edit";

interface Props {
  mode: FormMode;
  categories: CategoryItem[];
  initialValue?: VideoItem;
  onCancel?: () => void;
  onCreated?: (video: VideoItem) => void;
  onUpdated?: (video: VideoItem) => void;
}

export default function VideoForm({ mode, categories, initialValue, onCancel, onCreated, onUpdated }: Props) {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [title, setTitle] = useState(initialValue?.title || "");
  const [category, setCategory] = useState<VideoCategory>(
    (initialValue?.category as VideoCategory) || ("其他" as VideoCategory)
  );
  const [sourceUrl, setSourceUrl] = useState(initialValue?.sourceUrl || "");
  const [coverUrl, setCoverUrl] = useState(initialValue?.coverUrl || "");
  const [description, setDescription] = useState(initialValue?.description || "");
  const [durationSeconds, setDurationSeconds] = useState<number>(initialValue?.durationSeconds || 0);

  const isValid = useMemo(() => {
    return title.trim().length > 0 && category && sourceUrl.trim().length > 0;
  }, [title, category, sourceUrl]);

  useEffect(() => {
    setError(null);
  }, [title, category, sourceUrl, coverUrl, description, durationSeconds]);

  function genId() {
    return `v${Date.now()}`;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isValid) return;
    setSubmitting(true);
    setError(null);

    try {
      if (mode === "create") {
        const payload = {
          id: genId(),
          title: title.trim(),
          category,
          sourceUrl: sourceUrl.trim(),
          coverUrl: coverUrl.trim() || undefined,
          description: description.trim() || undefined,
          durationSeconds: Number(durationSeconds) || 0,
        };
        const res = await fetch("/api/videos", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.message || "新增失败");
        // data.data 可能是插入结果，重新获取单条或拼装
        const created: VideoItem = {
          id: payload.id,
          title: payload.title,
          category: payload.category as VideoCategory,
          sourceUrl: payload.sourceUrl,
          coverUrl: payload.coverUrl || "",
          description: payload.description,
          durationSeconds: payload.durationSeconds,
          publishedAt: undefined,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        };
        onCreated?.(created);
        setTitle("");
        setSourceUrl("");
        setCoverUrl("");
        setDescription("");
        setDurationSeconds(0);
      } else if (mode === "edit" && initialValue) {
        const payload = {
          title: title.trim(),
          category,
          sourceUrl: sourceUrl.trim(),
          coverUrl: coverUrl.trim() || undefined,
          description: description.trim() || undefined,
          durationSeconds: Number(durationSeconds) || 0,
        };
        const res = await fetch(`/api/videos/${initialValue.id}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
        const data = await res.json();
        if (!data.success) throw new Error(data.message || "更新失败");
        const updated: VideoItem = {
          ...initialValue,
          ...payload,
          updatedAt: new Date().toISOString(),
        } as VideoItem;
        onUpdated?.(updated);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "提交失败");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form className="space-y-3" onSubmit={handleSubmit}>
      {error && <div className="text-sm text-red-600">{error}</div>}
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <label className="space-y-1">
          <span className="block text-sm text-zinc-600 dark:text-zinc-300">标题</span>
          <input
            className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
            placeholder="请输入标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </label>

        <label className="space-y-1">
          <span className="block text-sm text-zinc-600 dark:text-zinc-300">分类</span>
          <select
            className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
            value={category}
            onChange={(e) => setCategory(e.target.value as VideoCategory)}
          >
            {categories.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </label>

        <label className="space-y-1">
          <span className="block text-sm text-zinc-600 dark:text-zinc-300">播放地址（m3u8/mp4）</span>
          <input
            className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
            placeholder="https://example.com/playlist.m3u8"
            value={sourceUrl}
            onChange={(e) => setSourceUrl(e.target.value)}
            required
          />
        </label>

        <label className="space-y-1">
          <span className="block text-sm text-zinc-600 dark:text-zinc-300">封面地址</span>
          <input
            className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
            placeholder="https://example.com/cover.jpg"
            value={coverUrl}
            onChange={(e) => setCoverUrl(e.target.value)}
          />
        </label>

        <label className="space-y-1">
          <span className="block text-sm text-zinc-600 dark:text-zinc-300">时长（秒）</span>
          <input
            type="number"
            className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
            placeholder="例如：3600"
            value={durationSeconds}
            onChange={(e) => setDurationSeconds(Number(e.target.value))}
            min={0}
          />
        </label>
      </div>

      <label className="space-y-1">
        <span className="block text-sm text-zinc-600 dark:text-zinc-300">简介</span>
        <textarea
          className="w-full rounded border border-zinc-300 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-zinc-400 dark:border-zinc-700 dark:bg-zinc-900"
          rows={4}
          placeholder="请输入简介"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
      </label>

      <div className="flex items-center gap-2">
        <button
          type="submit"
          disabled={!isValid || submitting}
          className="rounded bg-zinc-900 px-4 py-2 text-sm text-white disabled:cursor-not-allowed disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
        >
          {submitting ? "提交中..." : mode === "create" ? "新增视频" : "保存修改"}
        </button>
        {mode === "edit" && (
          <button
            type="button"
            className="rounded border border-zinc-300 px-3 py-2 text-sm hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-900"
            onClick={onCancel}
          >
            取消编辑
          </button>
        )}
      </div>
    </form>
  );
}


